
export function trim(strs){
    return strs.replace(/(^\s*)|(\s*$)/g,"")
}


export function ajax(options) {
	options = options || {};
	options.type = (options.type || "GET").toUpperCase();
	options.dataType = options.dataType || "application/x-www-form-urlencoded";
	var contentType = "application/x-www-form-urlencoded";
	switch(options.dataType) {
		case 'json':
			contentType = "application/json";
			break;
		default:
			break;
	}
	var params = formatParams(options.data, options.dataType);
	if (window.XMLHttpRequest) {
		var xhr = new XMLHttpRequest();
	} else {
		var xhr = new ActiveXObject('Microsoft.XMLHTTP');
	}
	
	xhr.onreadystatechange = function () {
		if (xhr.readyState == 4) {
			var status = xhr.status;
			if (status >= 200 && status < 300) {
				options.success && options.success(xhr.responseText, xhr.responseXML);
			} else {
				options.error && options.error(status);
			}
		}
	}
	
	if (options.type == "POST") {
		xhr.open("POST", options.url, true);
		xhr.setRequestHeader("Content-Type", contentType);
		xhr.timeout = 10000;
		xhr.ontimeout = function(){
			// 超时的操作
			console.log('timeout')
			xhr.abort(); //关闭请求

		}
		// 报错信息
		xhr.onerror = function(){
			console.log('busy');
		}
		xhr.send(params);
	} else {
		xhr.open(options.type, options.url + "?" + params, true);
		xhr.ontimeout = function(){
			// 超时的操作
			console.log('timeout');
			xhr.abort(); //关闭请求

		}
		// 报错信息
		xhr.onerror = function(){
			console.log('busy');
		}
		xhr.send(null);
	}
}

function formatParams(data, dataType) {
	var arr = [];
	if (dataType === 'json') {
		return JSON.stringify(data);
	} else {
		for (var name in data) {
			arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
		}
		arr.push(("v=" + Math.random()).replace(".",""));
		return arr.join("&");
	}
}

export function getUrlParam(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if (r != null) return unescape(r[2]); return null;
}

export function numberArray(start, end) {
    const result = [];
    for (let i = start; i < end; i++) {
        result.push(i);
    }
    return result
}

export function fixPercent(c1, c2, decimal) {
	var per = c1/c2;
	if(per == Infinity){
		return '∞'
	}
	return ((per || 0)*100).toFixed(decimal || 0)
}

export function merge(obj,extra) {
    return Object.assign({}, obj, extra)
}